import fs from 'fs'
import path from 'path'
import Koa from 'koa'
import sendFile from 'koa-send'
import {render} from "./dist/server/entry-server.js";
import manifest from "./dist/client/.vite/ssr-manifest.json";

const resolve = (p) => path.resolve(global.__dirname, p);
const clientRoot = resolve('dist/client');
const template = fs.readFileSync(resolve('dist/client/index.html'), 'utf-8');

(async () => {
    const app = new Koa();

    app.use(async (ctx) => {

        // 请求的是静态资源
        if (ctx.path.startsWith('/assets')) {
            await sendFile(ctx, ctx.path, {root: clientRoot});
            return;
        }

        const [appHtml, state, preloadLinks] = await render(ctx, manifest);

        const html = template
            .replace('<!--preload-links-->', preloadLinks)
            .replace('<!--pinia-state-->', state)
            .replace('<!--app-html-->', appHtml);

        ctx.type = 'text/html';
        ctx.body = html;
    });

    app.listen(8080, () => console.log('started server on http://localhost:8080'));
})();
